package kni.hoid;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

public class GoogleBooksService implements SearchService {
	private static final String API_KEY = "AIzaSyAg0846miymBTw7QBv6uJ5aENqAs5-Fpik";

	// public CharSequence test() {
	// Log.d("MY", "startujem");
	// List<Item> searchList = new ArrayList<Item>();
	// Item item = new Item();
	// item.setType(Item.Type.AUTHOR);
	// item.setWhat("Hawking");
	// searchList.add(item);
	//
	// List<Book> books = search(searchList);
	// StringBuffer result = new StringBuffer();
	// for (Book book : books) {
	// result.append(book).append("\n");
	// }
	// result.append("results: " + books.size());
	// return result.toString();
	// // return constructUri(searchList);
	//
	// // try {
	// // String request = constructUri();
	// // JSONObject json = HttpConnector.httpsGetRequest(request);
	// // return json.toString();
	// // } catch (JSONException ex) {
	// // return ex.toString();
	// // } catch (IOException e) {
	// // return e.toString();
	// // }
	// }

	public List<Book> search(List<Item> requestItems) {
		try {
			String request = constructUri(requestItems);
			JSONObject json = HttpConnector.httpsGetRequest(request);
			return parseJson(json);
		} catch (JSONException ex) {
			System.err.println(ex.toString());
			return Collections.<Book> emptyList();
		} catch (IOException e) {
			System.err.println(e.toString());
			return Collections.<Book> emptyList();
		}

		// List<List<Item>> allRequest = createAllRequests(requestItems);
		// Set<Book> result = new HashSet<Book>();
		// for (List<Item> itemList : allRequest) {
		// List<Book> partialResult = searchWithoutAllFields(itemList);
		// result.addAll(partialResult);
		// }
		// return new ArrayList<Book>(result);
	}

	// public List<List<Item>> createAllRequests(List<Item> requestItems) {
	// List<List<Item>> result = new ArrayList<List<Item>>();
	// result.add(requestItems);
	// for (Item item : requestItems) {
	// if (item.type == Type.ALL_FIELDS) {
	// // pokud se nekde objevuje all, tak odstranit a udelat dalsi
	// // List<>
	// requestItems.remove(item);
	// result.add(typeAllToItems(requestItems));
	// }
	// }
	// return result;
	// }

	// private List<Book> searchWithoutAllFields(List<Item> requestItems) {
	// try {
	// String request = constructUri(requestItems);
	// JSONObject json = HttpConnector.httpsGetRequest(request);
	// return parseJson(json);
	// } catch (JSONException ex) {
	// System.err.println(ex.toString());
	// return Collections.<Book> emptyList();
	// } catch (IOException e) {
	// System.err.println(e.toString());
	// return Collections.<Book> emptyList();
	// }
	// }

	// private static List<Item> typeAllToItems(List<Item> items) {
	// List<Item> result = new ArrayList<Item>();
	// for (Item item : items) {
	// if (item.type == Type.ALL_FIELDS) {
	// Item newItem = new Item();
	// newItem.setType(Type.AUTHOR);
	// newItem.setWhat(item.getWhat());
	// result.add(new Item());
	//
	// newItem = new Item();
	// newItem.setType(Type.ISBN);
	// newItem.setWhat(item.getWhat());
	// result.add(new Item());
	//
	// newItem = new Item();
	// newItem.setType(Type.TITLE);
	// newItem.setWhat(item.getWhat());
	// result.add(new Item());
	// } else {
	// result.add(item);
	// }
	// }
	// return result;
	// }

	private static String constructUri(List<Item> requestItems) {
		StringBuilder builder = new StringBuilder();
		builder.append("https://www.googleapis.com/books/v1/volumes?q=");
		// pokud jsou stejna pole, odstranit
		List<Item> reduced = reduceItems(requestItems);
		for (int i = 0; i < reduced.size(); i++) {
			Item item = reduced.get(i);
			if (item.getWhat() != null && !"".equals(item.getWhat())) {
				builder.append(itemToParam(reduced.get(i)));
				builder.append('&');
			}
		}
		builder.append("key=").append(API_KEY);
		builder.append("&maxResults=40");
		Log.d("MY", builder.toString());
		System.out.println("url: " + builder.toString());
		return builder.toString();
		// return
		// "https://www.googleapis.com/books/v1/volumes?q=flowers+inauthor:keyes&key=AIzaSyAg0846miymBTw7QBv6uJ5aENqAs5-Fpik";
	}

	private static List<Item> reduceItems(List<Item> requestItems) {
		// TODO: spojit atributy, pokud stejneho typu
		return requestItems;
	}

	private static String itemToParam(Item item) {
		switch (item.type) {
		case AUTHOR:
			return "inauthor:" + item.getWhat();
		case TITLE:
			return "intitle:" + item.getWhat();
		case ISBN:
			return "isbn:" + item.getWhat();
		case ALL_FIELDS:
			return item.getWhat();
		default:
			return "";
		}
	}

	private List<Book> parseJson(JSONObject requestResult) {
		try {
			JSONArray item = requestResult.getJSONArray("items");
			List<Book> result = new ArrayList<Book>(item.length());
			for (int i = 0; i < item.length(); i++) {
				try {
					JSONObject json = item.getJSONObject(i);
					Book book = new Book();
					JSONObject volumeInfo = json.getJSONObject("volumeInfo");
					// title
					String title = volumeInfo.getString("title");
					book.setTitle(title);
					// author
					JSONArray authors = volumeInfo.getJSONArray("authors");
					if (authors.length() != 0) {
						book.setAuthor(authors.getString(0));
					}
					// published
					String published = volumeInfo.getString("publishedDate");
					book.setPublishDate(published);
					// image
					book.setThumbnailURL(findImageUrl(volumeInfo));
					// isbn 10
					book.setIsbn(findIsbn(volumeInfo));
					// zdrojove url
					book.setOriginalUrl(findOriginalUrl(volumeInfo));
					result.add(book);
				} catch (JSONException e) {
				}
			}
			// Book testBook = new Book();
			// testBook.setAuthor("items: " + item.length());
			// result.add(testBook);
			return result;
		} catch (JSONException e) {
			return Collections.<Book> emptyList();
			// List<Book> result = new ArrayList<Book>();
			// Book test = new Book();
			// test.setAuthor("failed");
			// test.setTitle("JSONException");
			// result.add(test);
			// return result;
		}
	}

	private String findOriginalUrl(JSONObject volumeInfo) {
		try {
			String originalUrl = volumeInfo.getString("previewLink");
			return originalUrl;
		} catch (JSONException e) {
		}
		return null;
	}

	private String findImageUrl(JSONObject volumeInfo) {
		try {
			JSONObject images = volumeInfo.getJSONObject("imageLinks");
			String imageUrl = images.getString("smallThumbnail");
			return imageUrl;
		} catch (JSONException e) {
		}
		return null;
	}

	private String findIsbn(JSONObject volumeInfo) {
		try {
			JSONArray isbnIdentifiers = volumeInfo
					.getJSONArray("industryIdentifiers");
			for (int j = 0; j < isbnIdentifiers.length(); j++) {
				JSONObject obj = isbnIdentifiers.getJSONObject(j);
				String type = obj.getString("type");
				if ("ISBN_10".equals(type) || "ISBN_13".equals(type)) {
					String identifier = obj.getString("identifier");
					return identifier;
				}
			}
		} catch (JSONException e) {
		}
		return null;
	}
}
